package com.example.dbsample.web;

import com.example.dbsample.interceptor.AppIdThreadLocal;
import com.example.dbsample.model.enums.ResultCodeEnum;
import com.example.dbsample.model.http.LujsResponse;
import com.example.dbsample.util.net.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public abstract class BaseRest {
    public BaseRest() {
    }

    protected <T> LujsResponse<T> success() {
        return this.success((T) null);
    }

    protected <T> LujsResponse<T> success(T data) {
        return new LujsResponse(ResultCodeEnum.SUCCESS_200, data);
    }

    protected <T> LujsResponse<T> failure() {
        return this.failure(ResultCodeEnum.SYS_ERROR, (T) null);
    }
    protected <T> LujsResponse<T> failure(T data) {
        return this.failure(ResultCodeEnum.SYS_ERROR, data);
    }
    protected <T> LujsResponse<T> failure(ResultCodeEnum resultCodeEnum, T data) {
        return new LujsResponse(resultCodeEnum, data);
    }
    protected <T> LujsResponse<T> failure(ResultCodeEnum resultCodeEnum) {
        return new LujsResponse(resultCodeEnum);
    }

    protected String getLoginUid(HttpServletRequest request) {
        return request.getHeader("uid");
    }
    @Autowired
    private AppIdThreadLocal appIdThreadLocal;

    protected String getAppId() {
        return appIdThreadLocal.getAppId();
    }

    /**
     * 获取参数
     */
    protected String getParam(String name) {
        return WebUtils.getRequest().getParameter(name);
    }

    /**
     * 设置属性
     */
    protected void setAttr(String key, Object value) {
        WebUtils.getRequest().getSession().setAttribute(key, value);
    }

    /**
     * 获取HttpServletRequest
     */
    protected HttpServletRequest getHttpServletRequest() {
        return WebUtils.getRequest();
    }

    /**
     * 获取httpServletResponse
     */
    protected HttpServletResponse getHttpServletResponse() {
        return WebUtils.getResponse();
    }

    /**
     * 获取session：如果当前请求没有session，则创建一个
     */
    protected HttpSession getSession() {
        return WebUtils.getRequest().getSession();
    }

    /**
     * 获取session：如果当前请求没有session，true则创建一个，false则返回null
     */
    protected HttpSession getSession(boolean create) {
        return WebUtils.getRequest().getSession(create);
    }

    /**
     * 重定向
     */
    protected String redirect(String page) {
        return "redirect:".concat(page);
    }

    /**
     * 获取登录用户ID
     */
    protected String getLoginUserId() {
        return (String) getSession().getAttribute("loginUserId");
    }

}
